<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/16 0016
 * Time: 10:12
 */

namespace app\supplies\controller;

use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;
use think\Validate;
use app\Base;
use think\Cookie;

//----------------------------------------------
// 食材供应商WEB端接口
//----------------------------------------------
class Indexhome
{
    /********************************************/
    //首页信息
    /********************************************/

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-25
     * @rewriter:xx
     * @rewriter_date:
     * @description:首页-商户信息
     * @param:[]
     * @return[$result]
     */
    public function supplierInfo()
    {
        $data = Request::instance()->post();
        if (!empty($data['supplier_id'])){
            $supplier = Db::table('supplier')
                ->field('id, name, manager, manager_tel, tel, shop_introduction, send_time_type,
                 business, post_code, address, star, image,check_status,is_open,company_code,minimum')
                ->where(['id'=>$data['supplier_id']])
                ->find();
            $supplier['minimum'] = round($supplier['minimum'],2);
            if(is_int(intval($supplier['minimum']))){
                if (sizeof(explode ( '.', $supplier['minimum'] )) == 2) {
                    $supplier['minimum'] = $supplier['minimum'].'0￡';
                }else{
                    $supplier['minimum'] = $supplier['minimum'].'.00￡';
                }
            }
            if ($supplier){
                $base_id = explode(',',$supplier['business']);
                $name = '';
                foreach ($base_id as $k=>$v){
                    $res = Db::name('base_data')->field("concat_ws('/',name,name_english) as name")->where(['id'=>$v])->find();
                    $name = $name. $res['name'].',';
                }
                $result = Config::get('code.success');
                $supplier['business_name']  = rtrim($name, ',');
                $supplier['business']       = $supplier['business'];
                $result['supplier']         = $supplier;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);

    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-25
     * @rewriter:xx
     * @rewriter_date:
     * @description:首页-修改商户信息(提交)
     * @param:[]
     * @return[$result]
     */
    public function editInfo()
    {
        $data   =   Request::instance()->post();
        $var    =   explode(",",$data['business_name']);
        $v = '';
        foreach($var as $key =>$item){
            $item = str_replace("/",'_',$item);
            $item = preg_replace('/_.*/i', "", $item);
            $id = Db::table('base_data')->where(['name'=>['like','%'.$item],'flag'=>1,'parent_id'=>0])->value('id');
            $v .= $id.',';
        }
        $v = trim($v,",");
        $addressInfo =  Db::table('gb_postal_code')->where('postal_code',$data['post_code'])->find();
        self::checkArray($data);//验证id
        $list = self::comboArray($data,$v,$addressInfo);//组合数组
//		unset($list['minimum']);
//		unset($list['image']);
//		unset($list['image_show']);
        $list['minimum'] = floatval($list['minimum']);             // 去掉携带的￡ 符号（可能其他输入会报错）
        $result = Db::name('supplier')->where('id', $data['id'])->strict(false)->update($list);
        if ($result){
            $result = Config::get('code.success');
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }
    /**
     * 获取商户配送日程接口
     * @return json
     */
    public function getSendTimeBySupplierId(){
        $supplierId = input('supplier_id',0,'intval');
        if($supplierId <= 0){
            $res = config('code.error');
        }else{
            $supplier = Db::name('supplier')->where(['id'=>$supplierId])->find();
            if($supplier){
                $sendTime = self::getSupplierSendTime($supplier['id'],$supplier['send_time_type']);
                $data['supplier_id'] = $supplier['id'];
                $data['send_time_type'] = $supplier['send_time_type'];
                $data['send_time'] = $sendTime;
                $res = config('code.success');
                $res['data'] = $data;
            }else{
                $res = config('code.error');
            }
        }
        return json($res);
    }
    
    /**
     * 根据配送类型获取商户配送日程
     * @param int $id
     * @param int $type
     * @return array
     */
    protected static function getSupplierSendTime($id,$type){
        $list = Db::name('supplier_send_manage')->where(['supplier_id'=>$id])->select();
        switch ($type){
            case 1:
                $res = self::getSendTimeWeek($list);
                break;
            case 2:
                $res = self::getSendTimeMonth($list);
                break;
            default :
                $res = config('code.error');
                break;
        }
        return $res;
    }
    /**
     * 按周配送日程
     * @param array $list
     * @return array
     */
    protected static function getSendTimeWeek($list){
        $res = [];
        foreach ($list as $k=>$v){
            if($v['day'] <= 7){
                $res[$v['day']]['area'][] = $v['send_area'];
            }
        }
        return $res;
    }
    /**
     * 按月配送日程
     * @param array $list
     * @return array
     */
    protected static function getSendTimeMonth($list){
        $res = [];
        $month = date('t');
        for($day = 1;$day <= $month;$day++){
            foreach ($list as $k=>$v){
                if($day == $v['day']){
                    $res[$day]['area'][] = $v['send_area'];
                }
            }
        }
        return $res;
    }
    /**
     * 验证信息
     */
    protected static function checkArray($list){
        if(empty($list['id'])){
            $res = config('code.error');
            return $res;
        }
    }
    /**
     * 组合数组
     */
    protected static function comboArray($data,$v,$address){
        $list = [];
        $list['image']              = $data['image_show'];
        $list['name']               = $data['name'];
        $list['manager']            = $data['manager'];
        $list['manager_tel']        = $data['manager_tel'];
        $list['tel']                = $data['tel'];
        $list['shop_introduction']  = $data['shop_introduction'];
        $list['minimum']            = $data['minimum'];
        $list['business']           = $v;
        $list['post_code']          = $data['post_code'];
        $list['star']               = $data['star'];
        $list['company_code']       = $data['company_code'];
        $list['address']            = $data['address'];
        $list['admin_name1']        = $address['admin_name1'];
        $list['admin_name2']        = $address['admin_name2'];
        $list['admin_name3']        = $address['admin_name3'];
        return $list;
    }
}
